/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Logs;
import entities.RopaBlanca;
import entities.TipoTemporadas;
import entities.Usuarios;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import logica.ExcelJTableExporter;

/**
 *
 * @author root
 */
public class AltaTipoTemporadas extends JPanel {

    private final int SINPRIORIDAD = -1;
    private Logs logs;
    private String nombre;
    private boolean editando = false;
    private int colorBlanco = -1;
    private int rgbcolor = colorBlanco;
    private entities.TipoTemporadas t;
    private int jSpinnerAnterior;
    private final int maxPrioridades = 300;
    private Usuarios usuario;
    public static JFrame frame;

    public AltaTipoTemporadas(Usuarios usuario) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        habilitarBotones(false);
        this.usuario = usuario;
    }

    public JFrame getFrame() {
        return frame;
    }

    private Integer getIDTipoTemporadas(String nombre, int prioridad) {
        Query queryIDTipoTemporadas;
        TipoTemporadas tipoTemp;
        queryIDTipoTemporadas = entityManager.createNamedQuery("TipoTemporadas.findByNombrePrioridad");
        queryIDTipoTemporadas.setParameter("nombre", nombre);
        queryIDTipoTemporadas.setParameter("prioridad", prioridad);
        tipoTemp = (TipoTemporadas) queryIDTipoTemporadas.getSingleResult();
        return tipoTemp.getId();
    }

    public void setFrame(JFrame frame) {
        AltaTipoTemporadas.frame = frame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT t FROM TipoTemporadas t ORDER BY t.nombre ASC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        nombreLabel = new javax.swing.JLabel();
        prioridadLabel = new javax.swing.JLabel();
        guardarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        borrarButton = new javax.swing.JButton();
        elegirColorButton = new javax.swing.JButton();
        nombreField = new javax.swing.JTextField();
        cuadroColor = new javax.swing.JTextField();
        cancelarButton = new javax.swing.JButton();
        ayudaLabel = new javax.swing.JLabel();
        prioridadComboBox = new javax.swing.JComboBox();
        exportarExcelButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        masterTable.setColumnSelectionAllowed(true);
        masterTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombre}"));
        columnBinding.setColumnName("Nombre");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${RGBColor}"));
        columnBinding.setColumnName("RColor");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${prioridad}"));
        columnBinding.setColumnName("Prioridad");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        masterTable.getColumnModel().getColumn(0).setResizable(false);
        masterTable.getColumnModel().getColumn(0).setPreferredWidth(250);
        masterTable.getColumnModel().getColumn(1).setResizable(false);
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(30);
        masterTable.getColumnModel().getColumn(1).setCellRenderer(new renders.TipoRender());
        masterTable.getColumnModel().getColumn(2).setResizable(false);
        masterTable.getColumnModel().getColumn(2).setPreferredWidth(30);

        nombreLabel.setText("Nombre:");

        prioridadLabel.setText("Prioridad:");

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");
        guardarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        borrarButton.setBackground(new java.awt.Color(1, 154, 210));
        borrarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        borrarButton.setForeground(new java.awt.Color(255, 255, 255));
        borrarButton.setText("Borrar");
        borrarButton.setEnabled(false);
        borrarButton.addActionListener(formListener);

        elegirColorButton.setBackground(new java.awt.Color(1, 154, 210));
        elegirColorButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        elegirColorButton.setForeground(new java.awt.Color(255, 255, 255));
        elegirColorButton.setText("Elegir Color");
        elegirColorButton.addActionListener(formListener);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.nombre}"), nombreField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        nombreField.addKeyListener(formListener);

        cuadroColor.setEditable(false);
        cuadroColor.setEnabled(false);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(nombreLabel)
                                .addGap(9, 9, 9)
                                .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cuadroColor, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(elegirColorButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(prioridadLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(prioridadComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ayudaLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(exportarExcelButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(nuevoButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(borrarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cancelarButton)
                                .addGap(4, 4, 4)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(guardarButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {borrarButton, guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(exportarExcelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE)
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(nombreLabel)
                            .addComponent(elegirColorButton)
                            .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cuadroColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(prioridadLabel)
                            .addComponent(prioridadComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(53, 53, 53)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(guardarButton)
                                .addComponent(borrarButton)
                                .addComponent(nuevoButton)
                                .addComponent(cancelarButton))
                            .addComponent(ayudaLabel))))
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.KeyListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                AltaTipoTemporadas.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                AltaTipoTemporadas.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == borrarButton) {
                AltaTipoTemporadas.this.borrarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == elegirColorButton) {
                AltaTipoTemporadas.this.elegirColorButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                AltaTipoTemporadas.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                AltaTipoTemporadas.this.exportarExcelButtonActionPerformed(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == nombreField) {
                AltaTipoTemporadas.this.nombreFieldKeyReleased(evt);
            }
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                AltaTipoTemporadas.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                AltaTipoTemporadas.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private void setComboBox(int prioridadActual) {
        List<Integer> listaComboBox = new ArrayList<Integer>();
        boolean cambio = false;

        //Lleno una lista con valores entre 1 y 300 (actual máximo de prioridades)
        for (int i = 1; i <= maxPrioridades; i++) {
            listaComboBox.add(Integer.valueOf(i));
        }

        //Saco los que ya están utilizados
        for (TipoTemporadas tipoTemporada : list) {
            if (tipoTemporada.getPrioridad() != prioridadActual) {
                listaComboBox.remove(Integer.valueOf(tipoTemporada.getPrioridad()));
            }
        }

        //Limpio el ComboBox
        if (prioridadComboBox != null) {
            prioridadComboBox.removeAllItems();
        }

        //Y lo lleno con los valores que quedaron luego del filtro aplicado anteriormente
        for (Integer integer : listaComboBox) {
            prioridadComboBox.addItem(integer);
        }
    }

    public void elegirColor() {
        JColorChooser cc = new JColorChooser();
        AbstractColorChooserPanel[] panels = cc.getChooserPanels();
        JPanel p = new JPanel();
        panels[0].setBorder(
                new TitledBorder(panels[0].getDisplayName()));
        p.add(panels[0]);
        JPanel gui = new JPanel(new BorderLayout(2, 2));
        gui.add(p, BorderLayout.CENTER);
        gui.add(cc.getPreviewPanel(), BorderLayout.SOUTH);
        JOptionPane.showMessageDialog(null, gui);
        rgbcolor = cc.getColor().getRGB();
        cuadroColor.setEnabled(true);
        cuadroColor.setBackground(new Color(rgbcolor));
        masterTable.setValueAt(rgbcolor, masterTable.getSelectedRow(), 1);
    }

    public void refrescar() {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
        }
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        cuadroColor.setEnabled(false);
    }

    private void borrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarButtonActionPerformed
        int respuesta = JOptionPane.showConfirmDialog(null, "Desea confirmar el borrado del Tipo de Temporada?", "Borrado de Tipo de Temporada", JOptionPane.YES_NO_OPTION);
        if (respuesta == JOptionPane.YES_OPTION) {

            int[] selected = masterTable.getSelectedRows();
            List<entities.TipoTemporadas> toRemove = new ArrayList<entities.TipoTemporadas>(selected.length);
            try {
                for (int idx = 0; idx < selected.length; idx++) {
                    entities.TipoTemporadas t = list.get(masterTable.convertRowIndexToModel(selected[idx]));
                    toRemove.add(t);
                    logs = new Logs();
                    logs.setUsuario(usuario);
                    logs.setearObservaciones("Borrado", "TipoTemporadas", t.getId(), "AltaTipoTemporadas");
                    entityManager.persist(logs);
                    entityManager.remove(t);
                }
                list.removeAll(toRemove);
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();

                //guardar();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "No se puede Borrar la temporada, porque ya esta asignada a un rango de fecha", "Atención", WIDTH, null);

            }
            refrescar();
            limpiarBotones();
            habilitarBotones(false);
        }
    }//GEN-LAST:event_borrarButtonActionPerformed

    private void limpiarBotones() {
        nombreField.setText("");
        //   jSpinner1.setValue(1);
        rgbcolor = colorBlanco;
    }

    private void habilitarBotones(boolean estado) {
        nuevoButton.setEnabled(!estado);
        nombreField.setEnabled(estado);
        prioridadComboBox.setEnabled(estado);
        elegirColorButton.setEnabled(estado);
        guardarButton.setEnabled(estado);
        borrarButton.setEnabled(estado);
        cancelarButton.setEnabled(estado);
        masterTable.setEnabled(!estado);
        cuadroColor.setEnabled(estado);
        //ayudaEdicion.setVisible(!estado);
    }

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        t = new entities.TipoTemporadas();
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(t);
        list.add(t);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));

        habilitarBotones(true);
        editando = false;
        cuadroColor.setBackground(new Color(colorBlanco));
        borrarButton.setEnabled(false);
        setComboBox(-1);
    }//GEN-LAST:event_nuevoButtonActionPerformed
    private void guardar() {

        try {
            logs = new Logs();
            logs.setUsuario(usuario);
            t.setPrioridad((int) prioridadComboBox.getSelectedItem());
            if (t.getId() == null) {
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
                Integer idTipoTemporada = getIDTipoTemporadas(t.getNombre(), t.getPrioridad());
                logs.setearObservaciones("Alta", "TipoTemporadas", idTipoTemporada, "AltaTipoTemporadas");
            } else {
                logs.setearObservaciones("Modificación", "TipoTemporadas", t.getId(), "AltaTipoTemporadas");
            }
            entityManager.persist(logs);
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
        } catch (RollbackException rex) {
            if (rex.getMessage().contains("prioridad_UNIQUE")) {
                JOptionPane.showMessageDialog(this, "Ya existe la Prioridad", "Atención", JOptionPane.ERROR_MESSAGE, null);


            } else if (rex.getMessage().contains("rgbColor_UNIQUE")) {
                JOptionPane.showMessageDialog(this, "Ya existe el Color", "Atención", JOptionPane.ERROR_MESSAGE, null);

            }
            entityManager.getTransaction().begin();
            List<entities.TipoTemporadas> merged = new ArrayList<entities.TipoTemporadas>(list.size());
            for (entities.TipoTemporadas t : list) {
                merged.add(entityManager.merge(t));
            }
            list.clear();
            list.addAll(merged);
        }

    }

    private boolean existePrioridad(int prioridad) {
        int row = masterTable.getSelectedRow();
        int contador = 0;
        for (TipoTemporadas tipoTemporada : list.subList(0, list.size() - 1)) {
            if (row != contador) {
                if (tipoTemporada.getPrioridad() == prioridad) {
                    return true;
                }
            }
            contador++;
        }
        return false;
    }

    private boolean existeNombre(String nombre) {
        int row = masterTable.getSelectedRow();
        int contador = 0;
        for (TipoTemporadas tipotemporada : list.subList(0, list.size() - 1)) {
            if (row != contador) {
                if (tipotemporada.getNombre() == null ? nombre == null : tipotemporada.getNombre().equals(nombre)) {
                    return true;
                }
            }
            contador++;
        }
        return false;
    }

    private boolean existeColor(int color) {
        int row = masterTable.getSelectedRow();
        int contador = 0;
        for (TipoTemporadas tipoTemporada : list.subList(0, list.size() - 1)) {
            if (row != contador) {
                if (tipoTemporada.getRGBColor() == color) {
                    return true;
                }
            }
            contador++;
        }
        return false;
    }

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        if ("".equals(nombreField.getText())) {
            JOptionPane.showMessageDialog(this, "Complete el Nombre", "AtenciÃ³n", WIDTH, null);
            nombreField.requestFocus();
        } else if ((existeNombre(nombreField.getText()) || (existePrioridad((int) prioridadComboBox.getSelectedItem()) || existeColor(rgbcolor)))) {
            String guardarmensaje = "";
            if (existePrioridad((int) prioridadComboBox.getSelectedItem())) {
                guardarmensaje = guardarmensaje + "                     Prioridad\n";
            }
            if (existeColor(rgbcolor)) {
                guardarmensaje = guardarmensaje + "                     Color\n";
            }
            if (existeNombre((String) nombreField.getText())) {
                guardarmensaje = guardarmensaje + "                     Nombre\n";
            }
            JOptionPane.showMessageDialog(this, "Ya existe :\n" + guardarmensaje, "Atención", JOptionPane.ERROR_MESSAGE, null);

        } else {
            guardar();
            refrescar();
            limpiarBotones();
            habilitarBotones(false);
        }
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void elegirColorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_elegirColorButtonActionPerformed
        elegirColor();
    }//GEN-LAST:event_elegirColorButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        t = list.get(masterTable.getSelectedRow());
        if (masterTable.isEnabled()) {
            int prioridadActual = t.getPrioridad();
            setComboBox(prioridadActual);
            prioridadComboBox.setSelectedItem(masterTable.getModel().getValueAt(masterTable.getSelectedRow(), 2));
            cuadroColor.setBackground(new Color((int) masterTable.getModel().getValueAt(masterTable.getSelectedRow(), 1)));
            nombreField.setText((masterTable.getModel().getValueAt(masterTable.getSelectedRow(), 0)).toString());

        }
        habilitarBotones(true);
        editando = true;
        prioridadComboBox.setSelectedItem(t.getPrioridad());
    }//GEN-LAST:event_masterTableMouseClicked

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        refrescar();
        limpiarBotones();
        habilitarBotones(false);        // TODO add your handling code here:
    }//GEN-LAST:event_cancelarButtonActionPerformed
    int spinnerTemp = 0;
    private void nombreFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombreFieldKeyReleased
        String texto = nombreField.getText().toUpperCase();
        nombreField.setText(texto);
    }//GEN-LAST:event_nombreFieldKeyReleased

    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("En esta pantalla usted podra agregar,\n editar y eliminar tipos de temporadas");
    }//GEN-LAST:event_ayudaLabelMouseEntered

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Tipo Temporadas").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed
    int spinerTempOld;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton borrarButton;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JTextField cuadroColor;
    private javax.swing.JButton elegirColorButton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private javax.swing.JButton guardarButton;
    private java.util.List<entities.TipoTemporadas> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JTextField nombreField;
    private javax.swing.JLabel nombreLabel;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JComboBox prioridadComboBox;
    private javax.swing.JLabel prioridadLabel;
    private javax.persistence.Query query;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaTipoTemporadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaTipoTemporadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaTipoTemporadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaTipoTemporadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        final Usuarios usuario = user;

        /*
         * Create and display the form
         */
        AltaTipoTemporadas.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new AltaTipoTemporadas(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Organizacion   -   Tipo Temporadas   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
